import UIKit
import Alamofire
import GradientLoadingBar
import SwiftEventBus

class PromptViewController: UITableViewController {
    let notchGradientLoadingBar = NotchGradientLoadingBar(
        height: 3.0
    )
    
    var list:[Prompt] = []
    let cellIdentifier = "prompt_cell"
    override func viewDidLoad() {
        
        super.viewDidLoad()
        navigationItem.title = "角色指令大全"
        tableView.register(PromptCell.self, forCellReuseIdentifier: cellIdentifier)
        tableView.backgroundColor = .white
        notchGradientLoadingBar.fadeIn()
        getLocalJson()
    }
    
    override var wx_titleTextAttributes: [NSAttributedString.Key : Any]? {
           return [NSAttributedString.Key.foregroundColor: UIColor.black]
       }
    
    func getLocalJson(){
        if let json = StoreManager.getPromptJson(){
            self.parseJson(json: json)
        }
        getRolePromptList()
        
    }
    
    func getRolePromptList(){
        let parameters = BasicParameters()
        AFManager.sharedInstance.manager.request("\(baseUrl)diy_ai/list",method: .post,parameters: parameters,encoder: URLEncodedFormParameterEncoder.default).responseString { response in
            self.notchGradientLoadingBar.fadeOut()
            if let string = response.value{
                print(string)
                StoreManager.setPromptJson(json: string)
                self.parseJson(json: string)
            }else{
                
            }
        }
        
    }
    
    func parseJson(json: String?){
        
        if let string = json{
            let data = Data(string.utf8)
            do {
                let jsonDecoder = JSONDecoder()
                let promptResponse = try jsonDecoder.decode(PromptResponse.self, from: data)
                if !promptResponse.data.isEmpty{
                    self.list = promptResponse.data
                    self.tableView.reloadData()
                }
                
            } catch {
                print(error)
            }
        }
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! PromptCell
        cell.bindViewModel(list[indexPath.row])
        cell.selectionStyle = .none
        return cell
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return list.count
    }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 190
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        SwiftEventBus.post(EVENT_NAME_SELECT_ROLE, sender: list[indexPath.row])
        self.navigationController?.popViewController(animated: true)
    }
    
    
    
    
}
